package com.news.yp.baselibrary.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.news.yp.baselibrary.findbyid.ViewUtils;

/**
 * V层需要的泛型是P
 *
 * @param <P>
 */
public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements BaseView {
    private P mPresenter;
    private View rootView;
    //当前Fragment是否可见
    private boolean isFragmentVisible = false;
    //是否第一次创建
    private boolean hasInit = false;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.e("TAG", "-----setUserVisibleHint回调过来的值是：" + isVisibleToUser);
        if (isVisibleToUser) {
            isFragmentVisible = true;
        }
        if (rootView == null) { //fragment第一次初始化，此时rootView还没有被生成
            Log.e("TAG", "-----rootview为空，放弃");
            return;
        }
        onFragmentVisibleChange(isVisibleToUser);
//
//        if (!hasInit&&isFragmentVisible){ //Fragment可见，但是之前并没有被加载
//            onFragmentVisibleChange(true);
//            hasInit = true;
//            return;
//        }
//        //由可见变成不可见
//        if (isFragmentVisible){
//            onFragmentVisibleChange(false);
//            isFragmentVisible = false;
//            hasInit = true;
//        }
    }

    //丢给子类记载数据
    protected abstract void onFragmentVisibleChange(boolean b);

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = setView(inflater, container);
        ViewUtils.init(rootView, this);
        mPresenter = createPresenter();
        mPresenter.attach(this);
        initView();
        //    initData();
        //可见，但是并没有加载过
        if (isFragmentVisible && !hasInit) {
            Log.e("TAG", "onCreateView----");
            onFragmentVisibleChange(true);
        }
        return rootView;
    }


    //由子类去决定，生成哪一个presenter
    protected abstract P createPresenter();

    public P getPresenter() {
        return mPresenter;
    }

    /**
     * 返回一个View,填充一个Fragemnt自己的布局视图
     *
     * @param inflater
     * @param container
     * @return
     */
    protected abstract View setView(LayoutInflater inflater, ViewGroup container);

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 初始化View，比如findViewByID
     */
    protected abstract void initView();

    public void startActivity(Class<?> clazz) {
        startActivity(new Intent(getContext(), clazz));
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.detach();
    }
}
